/**
 * Copyright (c) 2018, wuxie All rights reserved.
 * qq:16349023,mail:16349023@qq.com
 * 未经许可禁止任何人通过任何渠道使用、修改源代码.
 * 项目名称 : wxcloud
 *
 * @version V1.0
 */
package cn.xo68.boot.auth.server.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 *  Spring cache configuration,
 * @author wuxie
 * @date 2018/8/6 21:25
 *
 */
//@Configuration
public class SpringCacheConfiguration {



    /**
     * redis spring cache
     * @param authRedisConnectionFactory
     * @return
     */
    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory authRedisConnectionFactory){

        // 使用Jackson2JsonRedisSerialize 替换默认序列化
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer=new GenericJackson2JsonRedisSerializer();

        RedisCacheConfiguration redisCacheConfiguration= RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration.prefixKeysWith("cache:");
        redisCacheConfiguration.entryTtl(Duration.ofMinutes(30));
        redisCacheConfiguration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(genericJackson2JsonRedisSerializer));

        Map<String, RedisCacheConfiguration> cacheConfigurations=new HashMap<>();

        //会话缓存配置
        RedisCacheConfiguration sessionCache= RedisCacheConfiguration.defaultCacheConfig();
        sessionCache.prefixKeysWith(ShiroSessionConfiguration.SESSION_CACHE_NAMESPACE+":");
        sessionCache.entryTtl(Duration.ofMinutes(60));
        sessionCache.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(genericJackson2JsonRedisSerializer));
        cacheConfigurations.put(ShiroSessionConfiguration.SESSION_CACHE_NAMESPACE, sessionCache);


        RedisCacheManager redisCacheManager= RedisCacheManager
                .RedisCacheManagerBuilder
                .fromConnectionFactory(authRedisConnectionFactory)
                .cacheDefaults(redisCacheConfiguration)
                .withInitialCacheConfigurations(cacheConfigurations)
                .build();
        //redisCacheManager.

        redisCacheManager.afterPropertiesSet();
        return redisCacheManager;
    }
}
